﻿using System;
using ProtoBuf;
using System.IO;

namespace Wala.Connection.ComConnections
{
    public class Convertor
    {
        /*
	 * encode a protobuf message to protocol packet, output is a array of byte
	 * for sending
	 */
        public static byte[] pb_encode(IExtensible pmessage, int type, long message_id,
                bool streaming)
        {
            MemoryStream temp = new MemoryStream();
            Serializer.Serialize(temp, pmessage);
            byte[] data = temp.ToArray();
            int size = data.Length + 8;

            if (message_id > 0)
                size += 8;

            byte[] buf = new byte[size];
            buf[0] = (byte)0xEE;
            buf[1] = (byte)0xEE;
            buf[2] = (byte)((size >> 8) & 0xFF);
            buf[3] = (byte)(size & 0xFF);
            buf[4] = (byte)((type >> 16) & 0xFF);
            buf[5] = (byte)((type >> 8) & 0xFF);
            buf[6] = (byte)(type & 0xFF);

            if (streaming)
                buf[7] = 1;
            else
                buf[7] = 0;

            if (message_id > 0)
            {
                buf[7] += 2;
                buf[8] = (byte)((message_id >> 56) & 0xFF);
                buf[9] = (byte)((message_id >> 48) & 0xFF);
                buf[10] = (byte)((message_id >> 40) & 0xFF);
                buf[11] = (byte)((message_id >> 32) & 0xFF);
                buf[12] = (byte)((message_id >> 24) & 0xFF);
                buf[13] = (byte)((message_id >> 16) & 0xFF);
                buf[14] = (byte)((message_id >> 8) & 0xFF);
                buf[15] = (byte)(message_id & 0xFF);
                Array.Copy(data, 0, buf, 16, data.Length);
                //System.arraycopy(data, 0, buf, 16, data.length);
            }
            else
            {
                Array.Copy(data, 0, buf, 8, data.Length);
                //System.arraycopy(data, 0, buf, 8, data.length);
            }
            return buf;
        }

        /* remove header of message */
        public static CoreMessage pb_decode(MemoryStream data)
        {
            CoreMessage ret = new CoreMessage(data);
            return ret;
        }

        /* remove header of message */
        //public static CoreMessage pb_decode(byte[] data)
        //{
        //    CoreMessage ret = new CoreMessage(data);
        //    return ret;
        //}
    }
}

